package ntu.p2p.past.messaging;

import java.io.IOException;

import ntu.p2p.past.test.Diff;

import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.Message;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.OutputBuffer;
import rice.p2p.past.PastContentHandle;
import rice.p2p.util.rawserialization.SimpleInputBuffer;


public class UpdateObjectMessage implements rice.p2p.commonapi.rawserialization.RawMessage {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static final short TYPE = 8;
	
	private Id contentId;
	private ObjectDifference difference;

	private static ObjectDifferenceContentDeserializer differenceDeserializer;
	
	public static void setDifferenceDeserializer(
			ObjectDifferenceContentDeserializer deserializer) {
		differenceDeserializer = deserializer;
	}
	
	public UpdateObjectMessage(Id contentId, ObjectDifference difference) {
		this.contentId = contentId;
		this.difference = difference;
	}
	
	@Override
	public int getPriority() {
		// TODO Auto-generated method stub
		return Message.DEFAULT_PRIORITY;
	}

	public Id getContentId() {
		return this.contentId;
	}
	
	public ObjectDifference getDifference() {
		return this.difference;
	}

	public static UpdateObjectMessage build(InputBuffer buf, Endpoint endpoint) throws IOException {
		return new UpdateObjectMessage(buf, endpoint);
  }  
  
	protected UpdateObjectMessage(InputBuffer buf, Endpoint endpoint) {
		try {
			contentId = endpoint.readId(buf, buf.readShort());
	    difference = this.differenceDeserializer.deserialize(buf, endpoint);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public short getType() {
		// TODO Auto-generated method stub
		return TYPE;
	}

	@Override
	public void serialize(OutputBuffer buf) throws IOException {
		System.out.println("Serializing update message");
		buf.writeShort(this.contentId.getType());
		this.contentId.serialize(buf);
		this.difference.serialize(buf);
		
	}
	
}
